package com.semp.gu.core.local;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.semp.gu.domain.Album;
import com.semp.gu.domain.local.LocalAlbum;
import com.semp.gu.domain.local.LocalAlbumElement;

public class AlbumService implements IAlbumService {

	private ILocalAlbumConverter		localAlbumConverter;
	private ILocalAlbumElementConverter	localAlbumElementConverter;

	public ILocalAlbumConverter getLocalAlbumConverter() {
		return localAlbumConverter;
	}

	public void setLocalAlbumConverter(ILocalAlbumConverter localAlbumConverter) {
		this.localAlbumConverter = localAlbumConverter;
	}

	public ILocalAlbumElementConverter getLocalAlbumElementConverter() {
		return localAlbumElementConverter;
	}

	public void setLocalAlbumElementConverter(ILocalAlbumElementConverter localAlbumElementConverter) {
		this.localAlbumElementConverter = localAlbumElementConverter;
	}

	public LocalAlbum getLocalAlbum(File folder) {
		if (folder == null || !folder.isDirectory()) {
			return null;
		}
		
		LocalAlbum localAlbum = localAlbumConverter.folderToLocalAlbum(folder);
		List<Album> subAlbums = new ArrayList<Album>();
		List<LocalAlbumElement> elements = new ArrayList<LocalAlbumElement>();
		
		File[] files = folder.listFiles();
		File processingFile;
		for (int i = 0; i < files.length; i++) {
			processingFile =files[i];
			// If file is directory it is an album
			if (processingFile.isDirectory()) {
				subAlbums.add(this.getLocalAlbum(processingFile));
			}
			// else, it is an element
			else {
				elements.add(localAlbumElementConverter.fileToLocalAlbumElement(processingFile));
			}
		}
		
		localAlbum.setSubAlbums(subAlbums);
		Collections.sort(elements, new Comparator<LocalAlbumElement>() {
			public int compare(LocalAlbumElement o1, LocalAlbumElement o2) {
				return o1.getDate().compareTo(o2.getDate());
			}
		});
		localAlbum.setElements(elements);
		
		return localAlbum;
	}

}
